package org.costas.classes
{
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.formatters.NumberFormatter;
	import mx.utils.ObjectUtil;
	
	[Event(name="PARSED", type="ParserNetworksListEvent")]
	[Event(name="ERROR",  type="ParserNetworksListEvent")]	
	
	//Parsing XML nodes and Objects with dashes in their names
	public class ParserNetworksList extends EventDispatcher
	{
		public var networksList:ArrayCollection = new ArrayCollection();
		private var kismetdata:XML;
		
		public function ParserNetworksList(kismetdata:XML, target:IEventDispatcher=null)
		{
			this.kismetdata = kismetdata;
			super(target);

		} // function KismetParser
		
		public function Parse():void {
			try {
				this.parseWirelessNetworks(kismetdata["wireless-network"]);
				dispatchEvent(new ParserNetworksListEvent(ParserNetworksListEvent.PARSED, this.networksList));
			} catch (ex:Error) {
				dispatchEvent(new ParserNetworksListEvent(ParserNetworksListEvent.ERROR));
				this.networksList = null;
			}
		} // function Parse
		
		private function parseWirelessNetworks(WirelessNetworks:XMLList):void {
			for each(var WirelessNetwork:XML in WirelessNetworks) {
				this.parseWirelessNetwork(WirelessNetwork);
			} //for each
		} // function parseWirelessNetworks
		
		private function parseWirelessNetwork(WirelessNetwork:XML):void {
			var frm:NumberFormatter = new NumberFormatter();
			frm.useNegativeSign = true;
			var net:Object = new Object();
			
			net.number = Number(WirelessNetwork["@number"].toString());
			net.type = WirelessNetwork["@type"].toString();
			
			net.essid = WirelessNetwork["SSID"]["essid"].toString();
			net.encryption = this.getEncryption(WirelessNetwork["SSID"]["encryption"]); 
			
			net.bssid = WirelessNetwork["BSSID"].toString();
			net.manuf = WirelessNetwork["manuf"].toString();
			net.channel = Number(WirelessNetwork["channel"].toString());
			frm.precision = 6;
			net.lat = frm.format(Number(WirelessNetwork["gps-info"]["avg-lat"].toString()));
			net.lon = frm.format(Number(WirelessNetwork["gps-info"]["avg-lon"].toString()));
			net.alt = frm.format(Number(WirelessNetwork["gps-info"]["avg-alt"].toString()));
			
			frm.precision = 2;
			net.power = frm.format((Number(WirelessNetwork["snr-info"]["min_signal_dbm"]) + Number(WirelessNetwork["snr-info"]["max_signal_dbm"])) / 2);
			
			net.clients = WirelessNetwork["wireless-client"].length() - 1;
			
			this.networksList.addItem(net);
			
		} // function parseWirelessNetwork
		
		private function getEncryption(values:Object):String {
			if (ObjectUtil.isSimple(values)) 
				return values.toString();
			var str:String = "";
			for each (var encryption:String in values){
				str = str + encryption + " ";
			}
			return str;
		} // function getEncryption
	} // class KismetParser
}